<template>
	<view>
		<home v-if="PageCur=='home'" @click="getUserInfo"></home>
		<user-center v-if="PageCur=='user-center'" @click="getUserInfo"></user-center>
		<view class="cu-bar tabbar bg-white shadow foot">
			<view class="action" @click="NavChange" data-cur="home">
				<view class='cuIcon-cu-image'>
					<image :src="'/static/tabbar/home' + [PageCur=='home'?'_cur':''] + '.png'"></image>
				</view>
				<view :class="PageCur=='home'?'text-nav-color':'text-gray'" class="text-bold">首页</view>
			</view>
			<view class="action" @click="NavChange" data-cur="user-center">
				<view class='cuIcon-cu-image image'>
					<image :src="'/static/tabbar/user' + [PageCur == 'user-center'?'_cur':''] + '.png'"></image>
				</view>
				<view :class="PageCur=='user-center'?'text-nav-color':'text-gray'" class="text-bold">用户中心</view>
			</view>
		</view>
	</view>
</template>

<script>
	var http = require('@/static/utils/request.js')
	export default {
		data() {
			return {
				PageCur: 'home',
				user: '',
				openid: '',
				itemList: [1, 2]
			}
		},
		created() {
			let _this = this
			//  从缓存中获取
			this.user = uni.getStorageSync('userInfo')
			if (this.user == undefined || '' == this.user) {
				// 从数库中获取用户信息
				this.loadUserInfoFromDB()
			}
		},
		methods: {
			loadUserInfoFromDB: function() {
				let _this = this
				wx.login({
					success: succ => {
						// 获取用户的openId
						http.getOpenId(succ.code).then(res => {
							_this.openid = res[1].data.openid
							http.getUserInfoByOpenId(res[1].data.openid).then(res2 => {
								_this.user = res2.data.data
								uni.setStorageSync('userInfo', _this.user)
							})
						})
					}
				})
			},
			NavChange: function(e) {
				if (this.user == undefined || '' == this.user) {
					this.getUserInfo(e)
				} else {
					this.PageCur = e.currentTarget.dataset.cur
				}
			},
			getUserInfo: function(e) {
				let _this = this
				// 获取失败调用用户的授权信息
				if (this.user == undefined || '' == this.user) {
					wx.getUserProfile({
						lang: 'zh_CN',
						desc: '提高用户体验',
						success: succ => {
							_this.user = succ.userInfo
							_this.user.openid = _this.openid
							uni.setStorageSync('userInfo', _this.user)
							http.saveUserInfo(_this.user).then(data => {
								_this.user = data.data
								if (e != undefined || e != null) {
									_this.PageCur = e.currentTarget.dataset.cur
								}
							})
						},
						fail: err => {
							uni.showModal({
								cancelText: '取消',
								confirmText: '确定',
								cancelColor: '#4CD964',
								confirmColor: '#ff0000',
								content: '拒绝授权可能导致功能无法正常使用',
								success: res => {
									if (res.confirm) {
										// 确定拒绝授权
									}
									if (res.cancel) {
										_this.getUserInfo(e)
									}
								}
							})
						}
					})
				}
			}
		}
	}
</script>

<style>
	.text-nav-color {
		color: #f39405;
	}
</style>
